package com.affectu.message.action;

import java.util.Date;
import java.util.List;

import org.jboss.seam.annotations.Name;

import com.affectu.dao.DAOBase;
import com.affectu.message.Message;
import com.affectu.user.User;

/**
 * Sep 24, 2008
 * 
 * @author daniel nathan
 */
@Name("messageIndexAction")
public class Index extends DAOBase {

	private List<Message> messages;

	private List<Message> newMessages;

	private List<Message> readedMessages;

	private String messageType;

	public String getMessageType() {
		try {
			Object obj = this.getRequestParam().get("msgType");
			if (Message.Status.NEW.toString().equals(obj.toString())) {
				messageType = "新消息";
			} else {
				messageType = "已读消息";
			}
		} catch (Exception ex) {
			this.logException(ex);
		}
		return messageType;

	}

	public List<Message> getMessages() {
		try {
			Object obj = this.getRequestParam().get("msgType");
			if (obj != null) {
				this.getSessionScope().put("msgType", obj);
			} else {
				obj = this.getSessionScope().get("msgType");
			}
			if (Message.Status.NEW.toString().equals(obj.toString())) {
				messages = this.getNewMessages();
			} else {
				messages = this.getReadedMessages();
			}
		} catch (Exception ex) {
			this.logException(ex);
		}
		return messages;
	}

	@SuppressWarnings("unchecked")
	public List<Message> getNewMessages() {
		try {
			String time = "(UNIX_TIMESTAMP(now())-UNIX_TIMESTAMP(m.sendDate))<1800";// 30
			// 分钟以内
			newMessages = em.createQuery(
					"select m from Message m where m.receiver=:receiver and ( m.status=:status or "
							+ time + " )  order by m.sendDate desc")
					.setParameter("receiver", this.getCurrentUser())
					.setParameter("status", Message.Status.NEW).list();
		} catch (Exception ex) {
			this.logException(ex);
		}

		return newMessages;
	}

	@SuppressWarnings("unchecked")
	public List<Message> getReadedMessages() {
		try {
			readedMessages = em
					.createQuery(
							"select m from Message m where m.receiver=:receiver and m.status=:status order by m.sendDate desc")
					.setParameter("receiver", this.getCurrentUser())
					.setParameter("status", Message.Status.READED).list();
		} catch (Exception ex) {
			this.logException(ex);
		}

		return readedMessages;
	}

	public String readMessage(Message msg) {
		try {
			msg.setStatus(Message.Status.READED);
			em.merge(msg);
		} catch (Exception ex) {
			this.logException(ex);
		}
		return "";
	}

	public String replyMessage(Message message, User user) {
		try {
			message.setSender(this.getCurrentUser());
			message.setReceiver(user);
			message.setStatus(Message.Status.NEW);
			message.setSendDate(new Date());
			em.persist(message);
		} catch (Exception ex) {
			this.logException(ex);
		}
		return "";
	}
}
